package com.hzit.order.interceptor;

import com.hzit.common.entity.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 类名：
 * 作者：WF
 * 功能：登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	//0. 将当前登录用户放到ThreadLocal线程局部变量中，只要同一个线程都可以互相访问
	public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();
	//1. 每个控制器方法执行前都会执行此方法进行拦截，返回值：true：放行，false: 不放行
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		//1.1 得到session
		HttpSession session = request.getSession();
		//1.2 得到session中保存的用户
		LoginUser loginUser = (LoginUser) session.getAttribute("loginUser");

		// String token = session.getAttribute("token") + "";
		// System.out.println("token = " + token);
		//1.3 用户名存在，证明登录过，就放行
		if(!Objects.isNull(loginUser)){
			//1.3.1 向线程本地变量中存放当前登录用户
			threadLocal.set(loginUser);
			return true;
		}
		//1.4 重定向的此页面，携带callback_url回退地址，保证以后可以回退到该购物车首页
		String requestURI = request.getRequestURI();

		response.sendRedirect("http://auth.hzit.com/auth/login?callback_url=http://order.hzit.com/" + requestURI);
		return false;
	}
}
